from liubao.ws import global_browsers

class mappath(dict):
    k = lambda self, host, uri: host if uri in ['', '/'] else host + uri
    def __call__(self, httpfile):
        env = httpfile.environ
        uri = fix('/', env['PATH_INFO'])
        fullpath = self.k(env['HTTP_HOST'], uri)
        p = fullpath.rindex(fullpath[-1]) + 1
        if '__ws__' == fullpath[-6:]:
            global_browsers(httpfile)
        else:            
            while 1:
                module = self.get(fullpath[:p])
                if hasattr(module, 'main'):
                    env['PATH_INFO'] = uri[p - len(env['HTTP_HOST']):]
                    return module.main(httpfile)
                p = fullpath.rfind('/', 0, p)
                if -1 == p:
                    return error404(httpfile)

#def quote_plus(s):
#    res = [c in alphabet and c or '%%%X' % ord(c) for c in s]
#    return ''.join(res).replace(' ', '+')

#def unquote_plus(s):
#    res = s.replace('+', ' ').split('%')
#    for i in xrange(1, len(res)):
#        item = res[i]
#        res[i] = chr(int(item[:2], 16)) + item[2:]
#    return ''.join(res)

def error404(httpfile):
    httpfile.start_response('404 Not Found', [('Content-Type', 'text/plain')], 5.)
    httpfile.write('The requested URL %s was not found '
                   'on this server.' % httpfile.environ['PATH_INFO'], 5.)
    httpfile.close(5.)

import re
fix = re.compile(r'/{2,}').sub; del re
#alphabet = set \
#('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-/ ')